#include <mcs51/at89x52.h>
#include "serial.h"


unsigned char Buffer[BUFFER_LENGTH]={0};
unsigned char ReadIndex=0;
unsigned char WriteIndex=0;
unsigned char UpdateFlag=0,LoopFlag=0,OverflowFlag=0;

void initSerial()
{
    SCON=0x50;
    TMOD|=0x20;
    PCON |= 0x80;
    TH1=SERIAL_TH1;
    TL1=SERIAL_TH1;
    ES=1;
    TR1=1;

    ReadIndex=0;
    WriteIndex=0;
}

void SendData(unsigned char Data)
{
    SBUF=Data;
    while(TI==0);
    TI=0;
}

unsigned char RecvData()
{
    unsigned char BufferData;
    BufferData=Buffer[ReadIndex];
    ReadIndex++;

    if(ReadIndex==BUFFER_LENGTH)
    {
        ReadIndex=0;
        LoopFlag=0;
    }

    if((ReadIndex==WriteIndex) && (LoopFlag==0))
    {
        UpdateFlag=0;
    }

    if(OverflowFlag)
    {
        OverflowFlag=0;
    }

    return BufferData;

}

void serailInterrupt() __interrupt (4) __using (1)
{
    if(RI==1)
    {
        RI=0;
        Buffer[WriteIndex]=SBUF;



        UpdateFlag=1;
        WriteIndex++;

        if(WriteIndex == BUFFER_LENGTH)
        {
            WriteIndex=0;
            LoopFlag=1;
        }

        if((WriteIndex >= ReadIndex) && (LoopFlag == 1))
        {
            OverflowFlag=1;
        }
    }
}
